﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using MWS.Processing.Interfaces;
using MWS.Processing.Serializers;

namespace MWS.Processing.Queues
{
    public class WindowsAzureQueue<T> : IQueue<T>
    {
        private readonly IXmlSerializer serializer;
        private readonly int deleteMessageMaxParallelism;
        private const int AzureMaxMessagesPerBatch = 32;

        private readonly StorageCredentialsAccountAndKey credentials;
        private readonly CloudQueueClient queueClient;
        private readonly CloudQueue queue;

        public string QueueName
        {
            get { return typeof (T).Name.ToLower(); }
        }

        public static class ConfigSettings
        {
            public const string AccountName = "Azure.AccountName";
            public const string AccountSharedKey = "Azure.AccountSharedKey";
            public const string QueueServiceEndpoint = "Azure.QueueServiceEndpoint";
        }

        public WindowsAzureQueue() : this(
            new XmlSerializer(),
            ConfigurationManager.AppSettings[ConfigSettings.AccountName],
            ConfigurationManager.AppSettings[ConfigSettings.AccountSharedKey],
            ConfigurationManager.AppSettings[ConfigSettings.QueueServiceEndpoint])
        {
        }


        public WindowsAzureQueue(IXmlSerializer serializer, string accountName, string accountSharedKey,
                                 string queueServiceEndpoint,
                                 int deleteMessageMaxParallelism = 4)
        {
            this.serializer = serializer;
            this.deleteMessageMaxParallelism = deleteMessageMaxParallelism;
            credentials = new StorageCredentialsAccountAndKey(accountName, accountSharedKey);
            queueClient = new CloudQueueClient(queueServiceEndpoint, credentials);

            queue = queueClient.GetQueueReference(QueueName);
            queue.CreateIfNotExist();
        }


        public void Clear()
        {
            throw new NotImplementedException();
        }

        public void Enqueue(T item)
        {
            var message = new CloudQueueMessage(serializer.Serialize(item).ToString());
            queue.AddMessage(message);
        }

        public IList<T> Dequeue(int maxItems)
        {
            maxItems = (maxItems > AzureMaxMessagesPerBatch) ? AzureMaxMessagesPerBatch : maxItems;

            var messages = queue.GetMessages(maxItems).ToList();

            Parallel.ForEach(
                messages,
                new ParallelOptions
                    {
                        MaxDegreeOfParallelism = deleteMessageMaxParallelism
                    },
                message => queue.DeleteMessage(message));

            return messages
                .Select(message => XElement.Parse(message.AsString))
                .Select(messageXml => serializer.Deserialize<T>(messageXml)).ToList();
        }

        public T Peek()
        {
            throw new NotImplementedException();
        }

        public bool Contains(T item)
        {
            throw new NotImplementedException();
        }
    }
}